#pragma once
#include <iostream>
#include <pthread.h>

namespace LockModule
{
    class Mutex
    {
    public:
        Mutex(const Mutex&) = delete;
        const Mutex& operator=(const Mutex&) = delete;
        Mutex()
        {
            int n = ::pthread_mutex_init(&_lock, nullptr);
            if (n != 0)
            {
                perror("Mutex Init fails");
            }
        }
        ~Mutex()
        {
            int n = ::pthread_mutex_destroy(&_lock);
            if (n != 0)
            {
                perror("Mutex destroy fails");
            }
        }
        void Lock()
        {
            int n = ::pthread_mutex_lock(&_lock);
            if (n != 0)
            {
                perror("Mutex lock fails");
            }
        }
        void Unlock()
        {
            int n = ::pthread_mutex_unlock(&_lock);
            if (n != 0)
            {
                perror("Mutex unlock fails");
            }
        }

    private:
        pthread_mutex_t _lock;
    }

    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }

        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex &_mtx;
    }
}